<?php

/**
 * Name: 系统通知记录模型层
 * User: Silent
 * Date: 2025-11-07
 * Time: 15:00:00
 */

namespace App\Models\Checkin;

use App\Models\Config\Employee;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class NotificationLog extends Model
{
    use HasFactory;

    protected $table = 'notification_logs';

    protected $guarded = [];

    protected $casts = [
        'related_date' => 'date:Y-m-d',
        'sent_at' => 'datetime:Y-m-d H:i:s',
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s',
    ];

    protected static $logName = 'notification_logs';

    // 通知类型常量
    const TYPE_SIGN_IN = 'sign_in';                    // 签到提醒
    const TYPE_DUTY_LEADER = 'duty_leader';            // 当班班长
    const TYPE_DUTY_SUPERVISOR = 'duty_supervisor';    // 值班领导
    const TYPE_ABNORMAL_CHECKIN = 'abnormal_checkin'; // 异常签到提醒

    // 发送状态常量
    const STATUS_PENDING = 'pending';  // 待发送
    const STATUS_SUCCESS = 'success';  // 成功
    const STATUS_FAILED = 'failed';    // 失败

    protected function serializeDate(DateTimeInterface $date): string
    {
        return $date->format('Y-m-d H:i:s');
    }

    /**
     * 关联接收人（员工）
     */
    public function recipient()
    {
        return $this->belongsTo(Employee::class, 'recipient_id');
    }

    /**
     * 获取通知类型文本
     */
    public function getNotificationTypeTextAttribute()
    {
        $typeMap = [
            self::TYPE_SIGN_IN => '签到提醒',
            self::TYPE_DUTY_LEADER => '当班班长提醒',
            self::TYPE_DUTY_SUPERVISOR => '值班领导提醒',
            self::TYPE_ABNORMAL_CHECKIN => '异常签到提醒'
        ];

        return $typeMap[$this->notification_type] ?? '未知';
    }

    /**
     * 获取发送状态文本
     */
    public function getSendStatusTextAttribute()
    {
        $statusMap = [
            self::STATUS_PENDING => '待发送',
            self::STATUS_SUCCESS => '发送成功',
            self::STATUS_FAILED => '发送失败'
        ];

        return $statusMap[$this->send_status] ?? '未知';
    }

    /**
     * 检查是否发送成功
     */
    public function isSent()
    {
        return $this->send_status === self::STATUS_SUCCESS;
    }

    /**
     * 标记为发送成功
     */
    public function markAsSent($result = null)
    {
        $this->update([
            'send_status' => self::STATUS_SUCCESS,
            'send_result' => $result,
            'sent_at' => now()
        ]);
    }

    /**
     * 标记为发送失败
     */
    public function markAsFailed($result = null)
    {
        $this->update([
            'send_status' => self::STATUS_FAILED,
            'send_result' => $result,
            'sent_at' => now()
        ]);
    }
}

